package com.ibm.cps.mqtt.paho;

import java.io.IOException;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;

public class MosquittoPublisher {

	MqttClient client;
	MqttConnectOptions conf;

	public MosquittoPublisher(String brokerURI, String clientId)
			throws MqttException {
		client = new MqttClient(brokerURI, clientId);
		conf = new MqttConnectOptions();
		conf.setCleanSession(true);
	}

	public void publish(String topicName, byte[] message)
			throws MqttPersistenceException, MqttException {
		client.connect(conf);
		MqttMessage mqttMessageage = new MqttMessage(message);
		client.subscribe(topicName, 2);

		// Continue waiting for messages until the Enter is pressed
		try {
			System.in.read();
		} catch (IOException e) {
			// If we can't read we'll just exit
		}
		client.disconnect();
		client.close();
	}

	public static void main(String[] args) {
		String server = "tcp://9.186.88.253:1883";
		String topicName = "test";
		byte[] message = "hello world".getBytes();
		try {
			MosquittoPublisher publisher = new MosquittoPublisher(server,
					"jing");
			publisher.publish(topicName, message);
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

}
